package com.harmontronics.hanma.paas.paas.service;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.harmontronics.hanma.paas.paas.consts.CommonConstants;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.consts.RedisConstant;
import com.harmontronics.hanma.paas.paas.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("hmCmsTokenService")
public class HmPaasTokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 使redis中的Token失效
     *
     * @param token
     */
    public void deleteToken(String token) {
        if (StringUtil.isEmpty(token)) {
            return;
        }
        //使Token失效
        stringRedisTemplate.delete(RedisConstant.PAAS_TOKEN_PREFIX + token);
    }

    /**
     * Token是否存在
     *
     * @param token
     * @return
     */
    public Boolean hasKey(String token) {
        if (StringUtil.isEmpty(token)) {
            return false;
        }
        //使Token失效
        return stringRedisTemplate.hasKey(RedisConstant.PAAS_TOKEN_PREFIX + token);
    }




    /**
     * 查询用户密码错误次数
     * 5分钟内连续错5次
     *
     * @param userName
     * @return
     */
    public JSONObject getPwdErrorNum(String userName) {
        if (StringUtil.isEmpty(userName)) {
            return null;
        }
        String loginCache = stringRedisTemplate.opsForValue().get(RedisConstant.PAAS_PWD_ERROR_NUM_PREFIX + userName);
        if (StringUtil.isEmpty(loginCache)) {
            return null;
        }
       return new JSONObject(loginCache);

    }

    /**
     * 设置用户密码错误次数
     * 5分钟内连续错进行计数5次,锁定5分钟
     *
     * @param userName
     * @return
     */
    public void setPwdErrorNum(String userName, Integer num) {
        if (StringUtil.isEmpty(userName)) {
            return;
        }
        JSONObject cacheObj = new JSONObject();
        cacheObj.put(CommonConstants.PWD_ERROR_NUM, num);
        cacheObj.put(CommonConstants.PWD_LOCK_BEGIN_TIME, System.currentTimeMillis());
        stringRedisTemplate.opsForValue().set(
                RedisConstant.PAAS_PWD_ERROR_NUM_PREFIX + userName,
                cacheObj.toString(),
                NumberEnum.FIVE.getNum(),
                TimeUnit.MINUTES);
    }


}
